//
//  CZNetWorkTools.swift
//  Weibo28
//
//  Created by Apple on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

//  请求方式
enum ReqeustType: Int {
    //  get请求
    case GET = 0
    //  post请求
    case POST = 1
}

class CZNetWorkTools: AFHTTPSessionManager {
    static let sharedTools: CZNetWorkTools = {
        let tools = CZNetWorkTools()
        //  设置可以接受的响应类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
    //  封装上传请求
    func requestUpload(url: String, params: AnyObject?, data: NSData, name: String, callBack: (response: AnyObject?, error: NSError?)->()) {
    
        POST(url, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            
            //  image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/
            
            //  data 图片对应二进制数据
            //  name 服务端需要的参数
            //  filename 服务端获取你传入图片的名字,一般服务端不会使用,它们自己会随机生成一个唯一标记的图片名
            //  mimeType 资源类型 application/octet-stream  不确定类型的数据
            formData.appendPartWithFileData(data, name: name, fileName: "test", mimeType: "application/octet-stream")
            
            }, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
            }) { (_, error) -> Void in
                callBack(response: nil, error: error)
        }
    }
    
    //  网络请求封装 get/ post
    func request(requestType: ReqeustType, url: String, params: AnyObject?, callBack: (response: AnyObject?, error: NSError?)->()) {
        //  定义一个成功的闭包
        let successClosure = { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
            //  成功的回调
            callBack(response: response, error: nil)
            
        }
        
        //  定义一个失败的闭包
        let failureClosure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
            //  失败的回调
            callBack(response: nil, error: error)
        
        }
        
        
        
        //  2.方式
        if requestType == .GET {
            GET(url, parameters: params, progress: nil, success: successClosure, failure: failureClosure)
            
        } else {
            POST(url, parameters: params, progress: nil, success: successClosure, failure: failureClosure)
        }
        
        
        //  1.方式
//        if requestType == .GET {
//            GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
//                
//                callBack(response: response, error: nil)
//                
//                }, failure: { (_, error) -> Void in
//                callBack(response: nil, error: error)
//            })
//        } else {
//            POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
//                callBack(response: response, error: nil)
//                }, failure: { (_, error) -> Void in
//                callBack(response: nil, error: error)
//            })
//        }
        
    }
    
    
    
    
}

//  发微博相关接口
extension CZNetWorkTools {
    
    //  发送图片微博接口
    func upload(access_token: String, status: String, image: UIImage, callBack: (response: AnyObject?, error: NSError?)->()) {
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        let params = [
            "access_token": access_token,
            "status": status
        ]
        //  图片转成二进制
        let data = UIImageJPEGRepresentation(image, 0.6)!
//        data.writeToFile("/Users/apple/Desktop/3.png", atomically: true)
        requestUpload(url, params: params, data: data, name: "pic", callBack: callBack)
        
//        POST(url, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
//            
//          //  image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/
//            
//            //  data 图片对应二进制数据
//            //  name 服务端需要的参数
//            //  filename 服务端获取你传入图片的名字,一般服务端不会使用,它们自己会随机生成一个唯一标记的图片名
//            //  mimeType 资源类型
//            formData.appendPartWithFileData(data, name: "pic", fileName: "test", mimeType: "image/jpeg")
//            
//            }, progress: nil, success: { (_, response) -> Void in
//                callBack(response: response, error: nil)
//            }) { (_, error) -> Void in
//                callBack(response: nil, error: error)
//        }
    }
    
    //  发送文字微博接口
    func update(access_token: String, status: String, callBack: (response: AnyObject?, error: NSError?)->()) {
        let url = "https://api.weibo.com/2/statuses/update.json"
        let params = [
            "access_token": access_token,
            "status": status
        ]
        
        request(.POST, url: url, params: params, callBack: callBack)
    
    }

}


//  首页相关接口
extension CZNetWorkTools {
    //  请求微博首页数据
    //  参数可以添加默认值,反之崩溃,也就是外界不给我们传值,默认给我传一个默认值
    func requestStatus(accessToken: String, maxId: Int64 = 0, sinceId: Int64 = 0, callBack: (response: AnyObject?, error: NSError?)->()) {
        //  创建url
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //  设置参数
        let params = [
            "access_token": accessToken,
            "max_id": "\(maxId)",
            "since_id": "\(sinceId)"
        ]
        print("haha-" + url + "?access_token=\(accessToken)")
        
        request(.GET, url: url, params: params, callBack: callBack)
    
    }
}

//  OAuth相关接口
extension CZNetWorkTools {
    //  获取accesstoken的接口
    func requestAccessToken(code: String, callBack: (response: AnyObject?, error: NSError?)->()) {
        //  创建url
        let url = "https://api.weibo.com/oauth2/access_token"
        //  设置参数
        let params = [
            "client_id": WeiboAppKey,
            "client_secret": WeiboAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WeiboRedirect_Uri
        ]
        
        request(.POST, url: url, params: params, callBack: callBack)
    }
    
    //  获取用户信息
    func requestUserInfo(userAccount: CZUserAcount, callBack: (response: AnyObject?, error: NSError?)->()) {
        //  url
        let url = "https://api.weibo.com/2/users/show.json"
        //  设置参数
        let params = [
            "access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)"
        ]
        request(.GET, url: url, params: params, callBack: callBack)
        
        
    }

    
    
}

